package com.xy.bizportdemo.task;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.provider.Telephony;
import android.util.Log;

import com.xy.bizportdemo.database.SmsDBHelper;
import com.xy.bizportdemo.database.SmsDBManager;
import com.xy.bizportdemo.database.entity.MessageItem;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2016/11/26.
 */

public class LoadSmsAsyncTask extends LoadBaseAsyncTask {
    private static final String TAG = "LoadSmsAsyncTask";

    public LoadSmsAsyncTask(Context context) {
        super(context);
    }

    @Override
    protected Void doInBackground(String... params) {
        // delete all system message if exist
        try {
            mContext.getContentResolver().delete(SmsDBHelper.URI_MESSAGE, "source=" + MessageItem.MESSAGE_SOURCE_SYSTEM, null);
        } catch (Throwable t) {
            Log.e(TAG, "doInBackground", t);
        }

        String[] projection = new String[] { "_id", "address", "body", "date", "type" };
        List<ContentValues> valueList = new ArrayList<ContentValues>();
        long start = Long.MAX_VALUE;
        long end = Long.MIN_VALUE;
        Cursor cursor = mContext.getContentResolver().query(Telephony.Sms.CONTENT_URI, projection, null, null, "date asc");
        if (cursor != null && cursor.moveToFirst()) {
            int current = 0;
            int totalCount = cursor.getCount();
            do {
                MessageItem item = new MessageItem();
                String phone = cursor.getString(1);
                String content = cursor.getString(2);
                item.setAddress(phone);
                item.setBody(content);
                String date = cursor.getString(3);
                long dateLong = Long.parseLong(date);
                if (start > dateLong) {
                    start = dateLong;
                }

                if (end < dateLong) {
                    end = dateLong;
                }

                item.setDate(date);
                item.setType(cursor.getInt(4));
                item.setSource(MessageItem.MESSAGE_SOURCE_SYSTEM);
                valueList.add(item.getContentValues());

                current++;
                publishProgress(current, totalCount);
            } while (cursor.moveToNext());
        }

        if (cursor != null) {
            cursor.close();
        }
        
        SmsDBManager.getInstance(mContext).insertBatch(valueList);
        return super.doInBackground(params);
    }
}
